package com.dmyang.service.impl;

import com.dmyang.common.pojo.HyResult;
import com.dmyang.dao.HyCommentMapper;
import com.dmyang.entity.HyComment;
import com.dmyang.entity.HyCommentExample;
import com.dmyang.service.CommentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by brss on 2017/8/10.
 */
@Service("commentServiceImpl")
public class CommentServiceImpl implements CommentService {

    @Autowired
    private HyCommentMapper commentMapper;
    /**
     * 分页查询出 某条文章的所有评论
     * @param pageSize 每页显示评论条数
     * @param belong 文章id
     * @param page 要显示第几页评论
     * @return Map：包含了 评论、总记录数，当前页 几个参数
     */
    @Override
    public Map<?, ?> showComment(Integer pageSize,Integer belong, Integer page) {
        //条件
        HyCommentExample example = new HyCommentExample();
        HyCommentExample.Criteria criteria = example.createCriteria();
        criteria.andBelongEqualTo(belong);
        //分页
        PageHelper.startPage(page,pageSize);
        List<HyComment> comments = commentMapper.selectByExample(example);
        //获取总记录条数
        PageInfo<HyComment> info = new PageInfo<>(comments);
        //计算总页数
        Long totalPages = 0L;
        if (info.getTotal()%pageSize==0){
            totalPages = info.getTotal()/pageSize;
        }else {
            totalPages = (info.getTotal()/pageSize) + 1;
        }
        //打包数据
        Map map = new HashMap<>();
        map.put("currentPage",page);
        map.put("totalPages",totalPages);
        map.put("comments",comments);
        return map;
    }

    /**
     * 添加一条评论
     * @param comment
     * @return
     * @throws Exception
     */
    @Override
    public HyResult addComment(HyComment comment) throws Exception {
        commentMapper.insertSelective(comment);

        return HyResult.build(200,"添加成功！");
    }
}
